<template>
  <div style="position: fixed;top: 200px;left: 400px;z-index: 9999;" v-if="showWurenji" class="storage-container">
    <div class="flex" style="position: absolute;top: 10px;left: 0;z-index: 999;width: 500px;height: 56px;background: #000;justify-content: space-between;align-items: center;">
      <div style="margin-left: 20px;font-size: 16px;color: #fff;font-weight: 600;">西宁街道</div>
      <img class="cursor" @click="showWurenji = false" src="./img/x.png" alt="" style="width: 20px;height: 20px;display: block;margin-right: 20px;" />
    </div>
    <div class="flex  col-top relative" id="storage-container" :style="{ width: rightShow ? '1000px' : '500px' }"
      style="padding-top: 10px;">

      <iframe src="https://fh.dji.com/share/MCQ7FpnfgKJ" frameborder="0"
        style="width: 500px;height: calc(100% - 20px);"></iframe>
      <img src="./img/right.png" alt=""
        style="width: 25px;height: 25px;position: absolute;right: 30px;bottom: 200px;z-index: 99;cursor: pointer;"
        @click="rightBox" v-if="!rightShow">
      <img src="./img/left.png" alt=""
        style="width: 25px;height: 25px;position: absolute;right: 15px;bottom: 200px;z-index: 99;cursor: pointer;"
        @click="rightBox" v-else>
      <div class="ai-swiper flex_1" ref="AIRefSwpier" v-show="rightShow">
        <div class="ai-content">
          <div class="flex col col-top" ref="messageContentRef">
            <div :class="item.role === 'user' ? 'use-message' : 'ai-message'" :style="{
              marginTop: index == 0 ? '0' : ''
            }" v-for="(item, index) in messageData" :key="index" v-html="mdCtx.render(item.content)"></div>
          </div>
        </div>
        <div class="input-box flex">
          <!-- @focus="focus" @blur="blur" -->
          <input type="text" v-model="value" />
          <!-- <button class="flex" @click="startRecorder">
            <img src="/img/voice.png" alt="" />
          </button> -->
          <button @click="submit">发送</button>
          <button @click="souSubmit">一键巡检</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">

import { onMounted, onUnmounted, ref, watchEffect, reactive, inject, watch } from "vue"
import { useWidgetStore } from "@mars/common/store/widget"
import MarkdownIt from "markdown-it"
const widgetStore = useWidgetStore()

const value = ref("")
const messageData = ref([])
const messageContentRef = ref()
const rightShow = ref(false)
const yijianxunjian = inject("yijianxunjian")
const showWurenji = inject("showWurenji")
const xiafarenwu = inject("xiafarenwu")
watch(yijianxunjian, (val, oldVal) => {
  if (val === "1") {
    rightShow.value = true
    setTimeout(() => {
      souSubmit()
    }, 100)
  }
})

watch(xiafarenwu, (val, oldVal) => {
  if (val !== "") {
    rightShow.value = true
    console.log(val)
    setTimeout(() => {
      xiafasouSubmit(val)
    }, 100)
  }
})

const rightBox = () => {
  rightShow.value = !rightShow.value
}
const mdCtx = new MarkdownIt({
  breaks: true,
  typographer: true,
  html: true
})
const xiafasouSubmit = (val) => {
  value.value = "请帮我发起" + val + "路线巡查"
  xiafarenwu.value = ""
  console.log(value.value)
  submit()
}
const souSubmit = () => {
  value.value = "请协助我用一号飞行器巡检园区"
  yijianxunjian.value = ""
  submit()
}
const submit = () => {
  if (!value.value) {
    return
  }

  messageData.value.push({
    role: "user",
    content: value.value
  })
  getResult(value.value)
  value.value = ""
  setTimeout(() => {
    if (!messageContentRef.value) {
      return
    }
    messageContentRef.value && (messageContentRef.value.scrollTop = messageContentRef.value?.scrollHeight)
    // openRef.value && (openRef.value.scrollTop = openRef.value.scrollHeight)
  })
}
const appKey = "app-J0yZT29HNiL8LgxwpyTtfkpC"

const isResponesEnd = ref(true)
let bufferObj
let txt
const resultObj = reactive({
  conversationId: "",
  taskId: "",
  messageId: ""
})
async function getResult(query) {
  if (!isResponesEnd.value) {
    return
  }
  isResponesEnd.value = false
  const resp = await fetch("http://117.172.206.47:8088/v1/chat-messages", {
    method: "post",
    headers: {
      "Content-Type": "application/json;audio/wav",
      Authorization: `Bearer ${appKey}`
    },
    body: JSON.stringify({
      conversation_id: resultObj.conversationId,
      user: "abc-123",
      inputs: {
        group_name: "西宁街道社区治理智能体",
        company_name: "西宁街道办",
        yuanqu_name: "鹭栖湖阵地"
      },
      query,
      response_mode: "streaming"
    })
  })
  // 获取流读取器
  const reader = resp?.body.getReader()
  // 字节数组转字符，创建文字解码器
  const decoder = new TextDecoder()

  // document.body.addEventListener("keydown", addStart)

  const str = ref("")

  messageData.value.push({
    role: "admin",
    content: str
  })

  const unicodeToChar = async (text) => {
    str.value += text
    // str.value = await mdCtx.render(str.value)

    messageContentRef.value && (messageContentRef.value.scrollTop = messageContentRef.value?.scrollHeight)
    // openRef.value && (openRef.value.scrollTop = openRef.value.scrollHeight)
    return text.replace(/\\u[0-9a-f]{4}/g, (_match, p1) => {
      return String.fromCharCode(parseInt(p1, 16))
    })
  }

  // 循环读取数据
  while (true) {
    const { done, value } = await reader.read()
    if (done) {
      return
    }

    // 解码
    txt += decoder.decode(value, { stream: true })
    const lines = txt.split("\n")

    try {
      lines.forEach((message) => {
        if (message.startsWith("data: ")) {
          try {
            bufferObj = JSON.parse(message.substring(6))
          } catch (e) {
            // mute handle message cut off
            // console.log(e)
            return
          }
          if (bufferObj.status === 400 || !bufferObj.event) {
            console.log("后端返回报错")
            return
          }
          if (bufferObj.event === "message" || bufferObj.event === "agent_message") {
            // can not use format here. Because message is splited.
            unicodeToChar(bufferObj.answer)
            resultObj.conversationId = bufferObj.conversation_id
            resultObj.taskId = bufferObj.task_id
            resultObj.messageId = bufferObj.id
          } else if (bufferObj.event === "agent_thought") {
            console.log(bufferObj)
          } else if (bufferObj.event === "message_file") {
            console.log(bufferObj)
          } else if (bufferObj.event === "message_end") {
            setTimeout(() => {
              messageContentRef.value && (messageContentRef.value.scrollTop = messageContentRef.value?.scrollHeight)
              // openRef.value && (openRef.value.scrollTop = openRef.value.scrollHeight)
            })
            isResponesEnd.value = true
          } else if (bufferObj.event === "message_replace") {
            console.log(bufferObj)
          } else if (bufferObj.event === "workflow_started") {
            console.log(bufferObj)
          } else if (bufferObj.event === "workflow_finished") {
            console.log(bufferObj)
          } else if (bufferObj.event === "node_started") {
            console.log(bufferObj)
          } else if (bufferObj.event === "node_finished") {
            console.log(bufferObj)
          }
          // else if (bufferObj.event === "tts_message") {
          //   !show.value && audioPlayer.play(bufferObj.audio)
          //   messageObj.conversationId = bufferObj.conversation_id
          //   messageObj.taskId = bufferObj.task_id
          //   messageObj.messageId = bufferObj.id
          // } else if (bufferObj.event === "tts_message_end") {
          //   tts_message_end.value = true
          // }
        }
      })
      txt = lines[lines.length - 1]
    } catch (e) {
      console.log(e)
      return
    }
  }
}
function addStart(e) {
  if (e.keyCode === 32 || e.keyCode === 12) {
    // startRecorder()
  }
}
// function startRecorder() {
//   if (!show.value && isResponesEnd.value) {
//     show.value = true
//     // stop_tts()
//     // audioPlayer.pause()

//     if (!audioContext) {
//       initAudio()
//     } else {
//       audioContext.resume()
//       connectWebSocket()
//     }
//   }
// }
// 关闭弹窗
const close = () => {
  widgetStore.dispatch("disable", "storageContainer")
}
</script>

<style lang="less">
.storage-container {
  background: none !important;
  box-shadow: none !important;
  border: none !important;
  padding: 15px 0px 0px !important;
  // box-sizing: border-box !important;
  width: auto !important;
  height: auto !important;
  z-index: 1500 !important;
}

.storage-container .mars-dialog__content {
  padding: 0 !important;
  overflow: visible !important;
}
</style>

<style lang="less" scoped>
#storage-container {
  border-image: url("/public/img/popupBox.png");
  border-image-slice: 5 5 5 5 fill;
  border-image-width: 12px 12px 12px 12px;
  border-image-outset: 0px 0px 0px 0px;
  border-image-repeat: stretch stretch;
  box-sizing: border-box;
  height: 425px !important;

  display: flex;
  gap: 20px;

  >div {
    flex: 0 0 auto;
    width: 100%;
  }

  .close {
    right: 32px;
    top: 0;
    transform: translateY(-30%);
    width: 28px;
    height: 28px;
    border-radius: 50%;
    border: 3px solid #2ca6ff;
    background: #000;
    cursor: pointer;

    &::after,
    &::before {
      content: "";
      width: 25px;
      height: 3px;
      background: #fff;
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%) rotate(45deg);
    }

    &::after {
      transform: translate(-50%, -50%) rotate(-45deg);
    }
  }
}

.ai-swiper {
  overflow: hidden;
  height: 100%;

  .ai-content {
    background: rgba(255, 255, 255, .4);
    border-radius: 20px;
    padding: 8px;
    gap: 24px;
    width: 100%;
    overflow: hidden;
    position: relative;
    height: calc(100% - 76px);

    >div {
      width: 100%;
      height: 100%;
      overflow: hidden auto;
      scrollbar-width: none;
      /* firefox */
      -ms-overflow-style: none;

      /* IE 10+ */
      &::-webkit-scrollbar {
        display: none;
        /* Chrome Safari */
      }

      div {
        max-width: 80%;
        line-height: 1.7;
        padding: 8px;
        border-radius: 10px;
        box-sizing: content-box;
        background: #fff;
        color: #252525;
        word-break: break-all;
        margin-top: 12px;
        // white-space: pre-line;

        &.use-message {
          margin-right: 0;
          margin-left: auto;
          background: #ffa9a9;
        }
      }
    }
  }

  .input-box {
    margin-top: 16px;
    height: 40px;
    border-radius: 40px;
    background: #fff;
    width: 100%;
    padding: 4px 4px 4px 12px;

    input {
      border: none;
      flex: 1;
      height: 100%;
      margin-right: 20px;
      outline: none;
      font-size: 14px;
    }

    img {
      flex: 0 0 auto;
      height: 100%;
    }

    button {
      flex: 0 0 auto;
      height: 100%;
      border: 1px solid #f33636;
      background: #730000;
      color: #fff;
      padding: 4px 16px;
      border-radius: 36px;
      cursor: pointer;
      letter-spacing: 1px;
      font-size: 14px;
      margin-left: 8px;
    }
  }
}

.flex_1 {
  flex: 1 !important;
}

.col {
  flex-direction: column;
}

.col-top {
  align-items: flex-start;
}

.flex {
  display: flex;
}

.relative {
  position: relative;
}
.cursor{
  cursor: pointer;
}
</style>
